package com.itboye.ihomebank.activity.finance;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.jinrong.TouZiJiLuAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.TouZiJiLuBean;
import com.itboye.ihomebank.bean.TouZiXQBean;
import com.itboye.ihomebank.activity.finance.fragment.AnQuanActivity;
import com.itboye.ihomebank.activity.finance.fragment.JiLuActivity;
import com.itboye.ihomebank.activity.finance.fragment.TouZiXQFragment;
import com.itboye.ihomebank.presenter.JinRongPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.CustomScrollView;
import com.itboye.ihomebank.util.DoubleUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 投资详情
 */
public class MyTouZiActivity extends BaseOtherActivity  implements Observer {

    TextView add_shap_title_tv,add_lift_tv;
    ImageView close_icon;
    List<String> list = new ArrayList<>();
    CustomScrollView scrollView;
    private Button btn_touzi;

    TextView txt_1;//预期年化收益
    TextView txt_3;//项目工期(单位：月)
    TextView txt_4; //总投资额
    TextView txt_5;//最大投资金额单位
    TextView txt_6;//最小投资金额单位
    TextView xm_title;//项目名称
    TextView xm_type;//项目类型
    TextView xm_qixi;//起息时间
    TextView xm_huikuan;//回款方式
    TextView xm_zhuanrang;//转让条件

    JinRongPresenter presenter;
    TouZiXQBean bean;
    String id;
    List<TouZiJiLuBean.A> listBean;
    TouZiJiLuAdapter adapter;

    //全部
    private TextView pictureTextView;
    //代付款
    private TextView movieTextView;
    //已付款
    private TextView musicTextView;

    //实现Tab滑动效果
    private ViewPager mViewPager;

    //动画图片
    private ImageView cursor;

    //动画图片偏移量
    private int offset = 0;
    private int position_one;
    private int position_two;

    //动画图片宽度
    private int bmpW;

    //当前页卡编号
    private int currIndex = 0;

    //存放Fragment
    private ArrayList<Fragment> fragmentArrayList;

    //管理Fragment
    private FragmentManager fragmentManager;

    public Context context;

    String qixian;
    String type;

    @Override
    protected int layout_id() {
        return R.layout.activity_my_tou_zi;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {
        add_shap_title_tv.setText("投资详情");
        add_lift_tv.setText("返回");

        presenter=new JinRongPresenter(this);
        id=getIntent().getStringExtra("id");
        type=getIntent().getStringExtra("type");

        if(type!=null){
            if(type.equals("5")){
                btn_touzi.setText("以售馨,不可购买");
                btn_touzi.setClickable(false);
            }
        }
        showProgressDialog("加载详情,请稍后...",true);
        presenter.detailP2p(id);

        listBean=new ArrayList<TouZiJiLuBean.A>();

     //   setListData();
        init();
    }


    private void init(){
        context = this;
        setStatusBarColor(R.color.blue_3);

        //初始化TextView
        InitTextView();
        //初始化ImageView
        InitImageView();
        //初始化Fragment
        InitFragment();
        //初始化ViewPager
        InitViewPager();

        // 短信登录发送过来的广播
        IntentFilter filter1 = new IntentFilter("goumaiend");
        registerReceiver(endReceiver, filter1);
    }
    BroadcastReceiver endReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            finish();
        };
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(endReceiver);
    }

    /**
     * 初始化头标
     */
    private void InitTextView() {
        //全部头标
        pictureTextView = (TextView) findViewById(R.id.picture_text);
        //待付款头标
        movieTextView = (TextView) findViewById(R.id.movie_text);
        //已付款头标
        musicTextView = (TextView) findViewById(R.id.music_text);

        //添加点击事件
        pictureTextView.setOnClickListener(new MyOnClickListener(0));
        movieTextView.setOnClickListener(new MyOnClickListener(1));
        musicTextView.setOnClickListener(new MyOnClickListener(2));
    }
    /**
     * 初始化动画
     */
    private void InitImageView() {
        cursor = (ImageView) findViewById(R.id.cursor);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        // 获取分辨率宽度
        int screenW = dm.widthPixels;

        bmpW = (screenW / 3);

        //设置动画图片宽度
        setBmpW(cursor, bmpW);
        offset = 0;

        //动画图片偏移量赋值
        position_one = (int) (screenW / 3.0);
        position_two = position_one * 2;

    }
    /**
     * 设置动画图片宽度
     * @param mWidth
     */
    private void setBmpW(ImageView imageView, int mWidth) {
        ViewGroup.LayoutParams para;
        para = imageView.getLayoutParams();
        para.width = mWidth;
        imageView.setLayoutParams(para);
    }

    /**
     * 将顶部文字恢复默认值
     */
    private void resetTextViewTextColor() {
        pictureTextView.setTextColor(getResources().getColor(R.color.black_two));
        movieTextView.setTextColor(getResources().getColor(R.color.black_two));
        musicTextView.setTextColor(getResources().getColor(R.color.black_two));
    }

    /**
     * 初始化Fragment，并添加到ArrayList中
     */
    private void InitFragment() {
        fragmentArrayList = new ArrayList<Fragment>();
        fragmentArrayList.add(new TouZiXQFragment(id));
        fragmentArrayList.add(new AnQuanActivity(id));
        fragmentArrayList.add(new JiLuActivity(id));

        fragmentManager = getSupportFragmentManager();

    }
    /**
     * 初始化页卡内容区
     */
    private void InitViewPager() {
        mViewPager = (ViewPager) findViewById(R.id.vPager);
        mViewPager.setAdapter(new MFragmentPagerAdapter(fragmentManager, fragmentArrayList));

        //让ViewPager缓存2个页面
        mViewPager.setOffscreenPageLimit(2);

        //设置默认打开第一页
        mViewPager.setCurrentItem(0);

        //将顶部文字恢复默认值
        resetTextViewTextColor();
        pictureTextView.setTextColor(getResources().getColor(R.color.blue_3));

        //设置viewpager页面滑动监听事件
        mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
    }

    public class MFragmentPagerAdapter extends FragmentPagerAdapter {

        //存放Fragment的数组
        private ArrayList<Fragment> fragmentsList;

        public MFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragmentsList) {
            super(fm);
            this.fragmentsList = fragmentsList;
        }

        @Override
        public Fragment getItem(int position) {

            return fragmentsList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentsList.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
        }
    }

    /**
     * 页卡切换监听
     * @author weizhi
     * @version 1.0
     */
    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
            Animation animation = null;
            switch (position) {

                //当前为页卡1
                case 0:
                    //从页卡1跳转转到页卡2
                    if (currIndex == 1) {
                        animation = new TranslateAnimation(position_one, 0, 0, 0);
                        resetTextViewTextColor();
                        pictureTextView.setTextColor(getResources().getColor(R.color.blue_3));
                    } else if (currIndex == 2) {//从页卡1跳转转到页卡3
                        animation = new TranslateAnimation(position_two, 0, 0, 0);
                        resetTextViewTextColor();
                        pictureTextView.setTextColor(getResources().getColor(R.color.blue_3));
                    }
                    break;

                //当前为页卡2
                case 1:
                    //从页卡1跳转转到页卡2
                    if (currIndex == 0) {
                        animation = new TranslateAnimation(offset, position_one, 0, 0);
                        resetTextViewTextColor();
                        movieTextView.setTextColor(getResources().getColor(R.color.blue_3));
                    } else if (currIndex == 2) { //从页卡1跳转转到页卡2
                        animation = new TranslateAnimation(position_two, position_one, 0, 0);
                        resetTextViewTextColor();
                        movieTextView.setTextColor(getResources().getColor(R.color.blue_3));
                    }
                    break;

                //当前为页卡3
                case 2:
                    //从页卡1跳转转到页卡2
                    if (currIndex == 0) {
                        animation = new TranslateAnimation(offset, position_two, 0, 0);
                        resetTextViewTextColor();
                        musicTextView.setTextColor(getResources().getColor(R.color.blue_3));
                    } else if (currIndex == 1) {//从页卡1跳转转到页卡2
                        animation = new TranslateAnimation(position_one, position_two, 0, 0);
                        resetTextViewTextColor();
                        musicTextView.setTextColor(getResources().getColor(R.color.blue_3));
                    }
                    break;
            }
            currIndex = position;

            animation.setFillAfter(true);// true:图片停在动画结束位置
            animation.setDuration(300);
            cursor.startAnimation(animation);

        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    ;

    /**
     * 头标点击监听
     *
     * @author weizhi
     * @version 1.0
     */
    public class MyOnClickListener implements View.OnClickListener {
        private int index = 0;

        public MyOnClickListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            mViewPager.setCurrentItem(index);
        }
    }
    private void setListData() {
//        for (int i = 0; i < 30; i++) {
//            list.add(i + "");
//        }
//        listView.setAdapter(new DataAdapter(list, this));
        scrollView.scrollTo(0, 0);
        scrollView.setFocusable(true);
        scrollView.setFocusableInTouchMode(true);
        scrollView.requestFocus();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.btn_touzi:
                Intent intent = new Intent(MyTouZiActivity.this, PurchaseActivity.class);
                intent.putExtra("title",bean.getTitle());
                intent.putExtra("id",id);
                intent.putExtra("bili",DoubleUtil.doubleTransform(bean.getExpected_annualize())+"%");
                intent.putExtra("shengyu",DoubleUtil.doubleTransform(bean.getRemaining_amount()));
                intent.putExtra("qixian",qixian);
                intent.putExtra("qitou",DoubleUtil.doubleTransform(bean.getMin_invest_amount()));
                startActivity(intent);
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == JinRongPresenter.tou_zi_xq_success) {
                bean= (TouZiXQBean) entity.getData();
                txt_1.setText(DoubleUtil.doubleTransform(bean.getExpected_annualize())+"%");
                if (Integer.parseInt(bean.getProject_duration_month())<=0) {
                    if (Integer.parseInt(bean.getProject_duration_day())>0) {
                        txt_3.setText("项目期限" + bean.getProject_duration_day() + "天");
                        qixian=bean.getProject_duration_day() + "天";
                    }else{

                    }
                }else {
                    txt_3.setText("项目期限" + bean.getProject_duration_month() + "个月");
                    qixian=bean.getProject_duration_month() + "个月";
                }
                txt_4.setText("项目总金额"+DoubleUtil.doubleTransform(bean.getTotal_money())+"元");
                txt_5.setText("剩余可投"+DoubleUtil.doubleTransform(bean.getRemaining_amount())+"元");
                txt_6.setText(DoubleUtil.doubleTransform(bean.getMin_invest_amount())+"元起投");
                xm_title.setText(bean.getTitle());
                xm_type.setText(bean.getDt_type_name());
                xm_qixi.setText("募集完成后"+bean.getDt_ttsci()+"个工作日起息");
                xm_huikuan.setText(bean.getDt_repayment_type_name());

            }
            if (entity.getEventType()==JinRongPresenter.tou_zi_xq_fail){
                ByAlert.alert(entity.getData());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }
}

